<template>
  <div class="page-view">
    <div class="map-view">
      <MyMap @ready="ready" ref="myMap">
        <MapGeo v-if="showLayer" :json="layers" :stroke="{ color: '#f0f', width: 2, }" fill="#ffffff00"></MapGeo>
        <MapMarker
          :data="marker"
          :scale="0.5"
          :cluster="false"
          :zIndex="999999"
          @show="clickPoint"
          @close="closePoint">
          <template>
            <div>
              <a-spin :spinning="loading">
                <a-descriptions title="位置信息" :column="1" bordered size="small">
                  <a-descriptions-item label="样点编号" :span="1">
                    {{ markerInfo['ydbh'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="坐落单位名称" :span="1">
                    {{ markerInfo['zldwmc'] }}
                  </a-descriptions-item>
                  <a-descriptions-item label="经纬度" :span="1">
                    {{ markerInfo['jd'], markerInfo['wd'] }}
                  </a-descriptions-item>
                  <a-descriptions-item label="土地利用类型" :span="1">
                    {{ markerInfo['tdlylx'] || '' }}
                  </a-descriptions-item>
                </a-descriptions>
                <br/>
                <a-descriptions title="土壤理化检测指标" :column="1" bordered size="small" style="margin-top: 10px;">
                  <a-descriptions-item label="阳离子交换量" :span="1">
                    {{ markerInfo['cec'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="有机质" :span="1">
                    {{ markerInfo['om'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="全氮" :span="1">
                    {{ markerInfo['tn'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="全磷" :span="1">
                    {{ markerInfo['tp'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="全钾" :span="1">
                    {{ markerInfo['tk'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="有效磷" :span="1">
                    {{ markerInfo['ap'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="缓效钾" :span="1">
                    {{ markerInfo['sk'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="速效钾" :span="1">
                    {{ markerInfo['ak'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="总铬" :span="1">
                    {{ markerInfo['cr'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="总镉" :span="1">
                    {{ markerInfo['cd'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="总铅" :span="1">
                    {{ markerInfo['pb'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="总砷" :span="1">
                    {{ markerInfo['as2'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="总汞" :span="1">
                    {{ markerInfo['hg'] || '' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="总镍" :span="1">
                    {{ markerInfo['ni'] || '' }}
                  </a-descriptions-item>
                </a-descriptions>
              </a-spin>
            </div>
          </template>
        </MapMarker>
      </MyMap>
    </div>
    <div class="select-filds">
      <a-form :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
        <a-form-item label="区域">
          <a-tree-select
            v-model="searchForm.xzqdm"
            :treeData="city"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :replaceFields="{
              value: 'dicCode',
              label: 'dicValue'
            }"
            placeholder="请选择区域"
            style="width: 100%">
          </a-tree-select>
        </a-form-item>
        <a-form-item label="指标类型">
          <a-select v-model="searchForm.type" style="width: 100%;" @change="changeType">
            <template v-for="item in type">
              <a-select-option :key="item.value" :value="item.value">{{ item.text }}</a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="指标">
          <a-select v-model="searchForm.quota" style="width: 100%;">
            <template v-for="item in type[searchForm.type].children">
              <a-select-option :key="item.value" :value="item.value">{{ item.text }}</a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="分析方法">
          <a-select v-model="searchForm.mode" style="width: 100%;">
            <a-select-option value="IDW">反距离加权</a-select-option>
            <a-select-option value="Kriging">普通克里金</a-select-option>
          </a-select>
        </a-form-item>
        <div style="text-align: center;">
          <a-button type="primary" @click="handleAnalysis"> 插值分析 </a-button>
        </div>
      </a-form>
    </div>

    <!-- 图例 -->
    <div class="map-legend">
      <div class="legend-body" v-if="legend.length">
        <template v-for="(item,index) in legend">
          <div class="img" :key="index">
            <span class="map-leg-icon" :style="`background: ${item.color}`"></span>
            <span>{{ item.title }}</span>
          </div>
        </template>
        <div v-if="valueData.length">
          <span style="padding-left: 0;">
            <img style="width: 16px; height: 16px" src="@/assets/icon/orange.png" alt="">
          </span>
          <span>异常点位</span>
        </div>
      </div>
      <div v-else class="line">
        <div class="line-top">高</div>
        <div class="line-botton">低</div>
        <div v-if="valueData.length" >
          <span style="padding-left: 0;">
            <img style="width: 16px; height: 16px" src="@/assets/icon/orange.png" alt="">
          </span>
          <span>异常点位</span>
        </div>
      </div>
    </div>

    <a-drawer
      placement="bottom"
      :visible="showTable"
      :mask="false"
      @close="showTable = !showTable "
      :height="330"
      :bodyStyle="{paddingBottom: '0px'}"
      title="异常点位"
    >
      <a-table
        rowKey="ydbh"
        :dataSource="valueData"
        size="small"
        :bordered="false"
        :columns="columns"
        :pagination="false"
        :customRow="customRow"
      >
      </a-table>
    </a-drawer>

    <div class="loading-warp" v-if="showLoading">
      <div class="loading-out ">
        <Loading></Loading>
        <div class="text">分析中</div>
      </div>
    </div>
  </div>
</template>

<script>
import { MyMap, MapGeo, MapMarker } from '@/map'
import { queryAllcity, queryCityGeo } from '@/api/common'
// import { queryInterpolate } from '@/api/interpolation'
import Loading from '@/components/loading'
import * as supermap from '@supermap/iclient-ol'
import TileLayer from 'ol/layer/Tile'
import TileGrid from 'ol/tilegrid/TileGrid'
// import Projection from 'ol/proj/Projection'
// import View from 'ol/View'
// import format from 'ol/format/GeoJSON'
import turf from 'turf'
import filedRange from '../list/gra.js'
import { Polygon } from 'ol/geom'
import { queryPointList } from '@/api/list'
import red from '@/assets/icon/red.png'
import orange from '@/assets/icon/orange.png'

const baseUrl = window.service.mapService + '/iserver/services/map-LYSP/rest/maps/平谷园林草地样点评价@业务数据'
const serviceUrl = window.service.mapService + '/iserver/services/spatialAnalysis-LYSP/restjsr/spatialanalyst'

let options

const filterPoint = {
  // cec: ['1101170201000098', '1101170201000212', '1101170201000355'],
  om: ['1101170301000060', '1101170301000098', '1101170301000331', '1101170301000355', '1101170305000321'],
  tn: ['1101170201000164', '1101170301000060', '1101170301000355', '1101170305000321'],
  tp: ['1101170201000111', '1101170201000126', '1101170201000128', '1101170201000164', '1101170201000219'],
  tk: ['1101170201000061', '1101170201000084', '1101170301000060']
}

const type = {
  lh: {
    text: '土壤理化性质',
    value: 'lh',
    children: [
      { text: '酸碱度', value: 'ph' },
      { text: '阳离子交换量', value: 'cec' }
    ]
  },
  yf: {
    text: '土壤养分',
    value: 'yf',
    children: [
      { text: '有机质', value: 'om' },
      { text: '全氮', value: 'tn' },
      { text: '全磷', value: 'tp' },
      { text: '全钾', value: 'tk' },
      { text: '有效磷', value: 'ap' },
      { text: '速效钾', value: 'ak' },
      { text: '有效硫', value: 'as1' }

    ]
  },
  hj: {
    text: '土壤环境',
    value: 'hj',
    children: [
      { text: '镉', value: 'cd' },
      { text: '汞', value: 'hg' },
      { text: '砷', value: 'as2' },
      { text: '铅', value: 'pb' },
      { text: '铬', value: 'cr' },
      { text: '镍', value: 'ni' }
    ]
  }
}

const columns = [
  {
    title: '序号',
    key: 'index',
    fixed: true,
    customRender: (text, record, index) => index + 1
  },
  {
    title: '样点编号',
    dataIndex: 'ydbh',
    fixed: true,
    key: 'ydbh'
  },
  {
    title: '坐落单位名称',
    dataIndex: 'zldwmc',
    key: 'zldwmc"'
  },
  {
    title: '有机质',
    dataIndex: 'om'
  },
  {
    title: '全氮',
    dataIndex: 'tn'
  },
  {
    title: '全磷',
    dataIndex: 'tp'
  },
  {
    title: '全钾',
    dataIndex: 'tk'
  },
  {
    title: '有效磷',
    dataIndex: 'ap'
  },
  {
    title: '速效钾',
    dataIndex: 'ak'
  },
  {
    title: '有效铁',
    dataIndex: 'afe'
  },
  {
    title: '有效锰',
    dataIndex: 'amn'
  },
  {
    title: '有效铜',
    valudataIndexe: 'acu'
  },
  {
    title: '有效锌',
    dataIndex: 'azn'
  },
  {
    title: '有效硼',
    dataIndex: 'ab'
  },
  {
    title: '有效钼',
    dataIndex: 'amo'
  }
]

export default {
  name: 'Interpolation',
  components: {
    MapMarker,
    MyMap,
    MapGeo,
    Loading
  },
  data () {
    this.columns = columns
    this.type = type
    this.tempLayer = undefined
    return {
      myMap: null,
      loading: false,
      showLoading: false,
      searchForm: {
        xzqdm: '110117',
        type: 'lh',
        quota: 'ph',
        mode: 'IDW'
      },
      city: [],
      layers: undefined,
      showLayer: false,
      showTable: false,
      legend: [],
      marker: [],
      markerInfo: {},
      valueData: []
    }
  },
  created () {
    this.fetchCity()
    this.handleAnalysis()
  },
  methods: {
    ready (map) {
      this.myMap = map
      new supermap.MapService(baseUrl).getMapInfo().then((serviceResult) => {
        const mapJSONObj = serviceResult.result
        options = supermap.TileSuperMapRest.optionsFromMapJSON(baseUrl, mapJSONObj)
        // options.layersID = '[0]'
        const layer = new TileLayer({
          source: new supermap.TileSuperMapRest(options)
        })
        this.myMap.addLayer(layer)
      })
    },
    changeType () {
      this.searchForm.quota = this.type[this.searchForm.type].children[0].value
    },
    customRow (record) {
      return {
        on: {
          click: () => {
            this.clickPoint({ items: [ { ...record } ] })
          }
        }
      }
    },
    async clickPoint (marker) {
      this.marker = this.marker.map(point => {
        if (point.ydbh === marker.items[0].ydbh) {
          this.$refs.myMap.moveTo([ point.jd, point.wd ])
          return {
            ...point,
            style: undefined,
            src: red
          }
        } else {
          return {
            ...point,
            ...this.setMarkerStyle(point)
          }
        }
      })
      this.markerInfo = marker.items[0]
      this.loading = false
    },
    closePoint () {
      this.marker = this.marker.map(point => {
        return {
          ...point,
          coordinate: [Number(point.jd), Number(point.wd)],
          ...this.setMarkerStyle(point)
        }
      })
    },

    setMarkerStyle (item) {
      const filter = filterPoint[this.searchForm.quota] || []
      if (filter.includes(item.ydbh)) {
          return {
            style: undefined,
            src: orange
          }
        } else {
          return {
            style: {
              fill: '#fff',
              radius: 3
            }
          }
        }
    },
    async fetchCity () {
      const { data } = await queryAllcity()
      this.city = data[0].children
    },

    async handleChange () {
      this.layers = undefined
      if (this.searchForm.xzqdm) {
        const { data } = await queryCityGeo({
          xzqdm: this.searchForm.xzqdm
        })
        this.layers = JSON.parse(data)
      }
    },

    // 分析
    async handleAnalysis () {
      await this.handleChange()
      const points = await queryPointList({
        xzqdm: this.searchForm.xzqdm
      })
      // 过滤耕地类型
      const data = points.data.filter(item => {
        return !(/^01\d/.test(item.tdlylx))
      })

      this.marker = data.map(item => {
        return {
          ...item,
          coordinate: [ Number(item.jd), Number(item.wd) ],
          ...this.setMarkerStyle(item)
        }
      })
      // 异常点位表单
      const filter = filterPoint[this.searchForm.quota] || []
      if (filter.length) {
        this.valueData = data.filter(item => {
          return filter.includes(item.ydbh)
        })
        this.showTable = true
      } else {
        this.showTable = false
        this.valueData = []
      }

      if (this.tempLayer) {
        this.myMap.removeLayer(this.tempLayer)
        this.tempLayer = undefined
      }

      if (this.searchForm.mode === 'IDW') {
        this.idwAnalyst()
      } else if (this.searchForm.mode === 'Kriging') {
        this.krigingAnalyst()
      }
    },

    // IDW
    idwAnalyst () {
      this.showLoading = true
      const filterStr = filterPoint[this.searchForm.quota] || [].toString()
      const attributeFilter = filterStr ? `YDBH NOT IN ('${filterStr}')` : ''
      const interpolationAnalystParameters = new supermap.InterpolationIDWAnalystParameters({
        filterQueryParameter: {
          attributeFilter: attributeFilter
        },
        dataset: '平谷园林草地样点评价@业务数据3',
        // 插值分析结果数据集的名称
        outputDatasetName: 'IDW_result',
        // 插值分析结果数据源的名称
        outputDatasourceName: '业务数据3',
        zValueFieldName: this.searchForm.quota,
        power: 2,
        resolution: 0.0006,
        pixelFormat: 'BIT16',
        bounds: new Polygon(this.layers.coordinates[0]).getExtent(),
        clipParam: new supermap.ClipParameter({
          clipRegion: new Polygon(this.layers.coordinates[0]),
          isClipInRegion: true
        })
      })
      new supermap.SpatialAnalystService(serviceUrl)
        .interpolationAnalysis(interpolationAnalystParameters)
        .then((serviceResult) => {
          this.showLoading = false
          // 获取服务端返回的数据
          const interpolationAnalystResult = serviceResult.result
          this.showAnalysisResultThemeGridRange(interpolationAnalystResult)
          interpolationAnalystParameters.destroy()
        })
    },

    // Kriging
    krigingAnalyst () {
      this.showLoading = true
      const that = this
      const filterStr = filterPoint[this.searchForm.quota] || [].toString()
      const attributeFilter = filterStr ? `YDBH NOT IN ('${filterStr}')` : ''
      const interpolationAnalystParameters = new supermap.InterpolationKrigingAnalystParameters({
        // 用于做插值分析的数据源中数据集的名称
        dataset: '平谷园林草地样点评价@业务数据3',
        // 插值分析结果数据集的名称
        outputDatasetName: 'Kriging_result',
        // 插值分析结果数据源的名称
        outputDatasourceName: '业务数据3',
        // 结果栅格数据集存储的像素格式
        pixelFormat: supermap.PixelFormat.BIT16,
        // 采取固定点数查找参与运算点的方式
        searchMode: 'QUADTREE',
        type: 'KRIGING',
        // 属性过滤条件
        filterQueryParameter: {
          attributeFilter: attributeFilter
        },
        // 存储用于进行插值分析的字段名称
        zValueFieldName: this.searchForm.quota,
        resolution: 0.0001,
        // searchRadius: '0',
        // 固定点数查找方式下，参与插值运算的点数默认为12
        expectedCount: 12,
        bounds: new Polygon(this.layers.coordinates[0]).getExtent(),
        clipParam: new supermap.ClipParameter({
          clipRegion: new Polygon(this.layers.coordinates[0]),
          isClipInRegion: true
        })
      })
      new supermap.SpatialAnalystService(serviceUrl)
        .interpolationAnalysis(interpolationAnalystParameters)
        .then(function (serviceResult) {
          that.showLoading = false
          // 获取服务端返回的数据
          const interpolationAnalystResult = serviceResult.result
          that.showAnalysisResultThemeGridRange(interpolationAnalystResult)
          interpolationAnalystParameters.destroy()
        })
    },
    getRanecolor () {
      // const color1 = new supermap.ServerColor(170, 240, 233)
      if (filedRange[this.searchForm.quota]) {
        this.legend = filedRange[this.searchForm.quota]
        const colors = filedRange[this.searchForm.quota].map(item => {
          // 获取 hex 颜色RGB值
          const hexColor = item.color.replace('#', '')
          const r = parseInt(hexColor.substring(0, 2), 16)
          const g = parseInt(hexColor.substring(2, 4), 16)
          const b = parseInt(hexColor.substring(4, 6), 16)

          return new supermap.ThemeGridRangeItem({
            caption: item.title,
            start: item.min || 0,
            end: item.max || 1000,
            color: new supermap.ServerColor(r, g, b)
          })
        })
        return colors
      }
      return undefined
    },
    // 构造栅格专题图
    showAnalysisResultThemeGridRange (interpolationAnalystResult) {
      this.showLoading = true
      const item = this.getRanecolor()

      const rangeOptions = {
        reverseColor: false,
        rangeMode: supermap.RangeMode.EQUALINTERVAL,
        rangeParameter: 32
      }

      if (!item) {
        rangeOptions.colorGradientType = supermap.ColorGradientType.CYAN_BLUE
      } else {
        // 栅格分段专题图子项数组
        rangeOptions.items = item
      }

      const themeGridRange = new supermap.ThemeGridRange(rangeOptions)
      const themeParameters = new supermap.ThemeParameters({
        // 制作专题图的数据集
        datasetNames: [interpolationAnalystResult.dataset.split('@')[0]],
        dataSourceNames: ['业务数据3'],
        joinItems: null,
        themes: [themeGridRange]
      })
      new supermap.ThemeService(baseUrl).getThemeInfo(themeParameters)
        .then((serviceResult) => {
          const result = serviceResult.result
          if (result && result.newResourceID) {
            const themeLayer = new TileLayer({
              id: 'themeLayer',
              source: new supermap.TileSuperMapRest({
                url: baseUrl,
                noWrap: true,
                cacheEnabled: false,
                layersID: result.newResourceID,
                tileGrid: new TileGrid({
                  extent: turf.bbox(this.layers),
                  resolutions: options.tileGrid.getResolutions()
                }),
                transparent: true
              }),
              zIndex: 6
            })
            this.tempLayer = themeLayer
            this.myMap.addLayer(themeLayer)
            this.showLoading = false
            this.showLayer = true
          }
          themeGridRange.destroy()
          themeParameters.destroy()
        })
    }
  }
}
</script>
<style lang="less" scoped>
.page-view {
  position: relative;
  height: 100%;
  .map-view {
    position: absolute;
    top: -24px;
    right: -24px;
    bottom: -24px;
    left: -24px;
  }
}
.select-filds {
  position: absolute;
  top: 0;
  right: 0;
  padding: 16px;
  width: 360px;
  border-radius: 4px;
  background: #ffffff;
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
  .group {
    font-size: 14px;
  }
}
.loading-warp {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.03);
  .loading-out {
    display: inline-block;
    padding: 16px 24px;
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.5);
  }
  .text {
    text-align: center;
    color: #ffffff;
  }
}
.map-legend {
  position: absolute;
  right: 0;
  bottom: 0;
  padding: 24px 0 24px 24px;
  background: #ffffff;
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
  .legend-body {
    overflow-y: auto;
    padding-right: 24px;
    max-height: 300px;
  }
  img {
    width: 30px;
  }
  span {
    padding-left: 16px;
  }
  .map-leg-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    vertical-align: middle;
  }
  .line {
    position: relative;
    display: flex;
    justify-content: space-between;
    margin-right: 24px;
    padding-left: 20px;
    height: 100px;
    flex-flow: column;
    &::after {
      position: absolute;
      top: 0;
      left: 0;
      width: 10px;
      height: 100%;
      background: linear-gradient(0deg, #00ffff 0%, #0000ff 100%);
      content: '';
    }
  }
}
</style>
